package com.wonders.framework.util;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

import com.wonders.framework.exception.FrameworkException;

/**
 * 流工具
 * 
 * @author WuBin
 * 
 */
public class StreamUtil {

	private static final int BUFFER_SIZE = 512;

	/**
	 * 读取流
	 * 
	 * @param inputStream
	 *            输入流
	 * @param len
	 *            读取长度
	 * @return 指定长度流
	 */
	public static byte[] read(DataInputStream inputStream, int len) {
		ByteArrayOutputStream baos = null;
		DataOutputStream dataOutputStream = null;
		try {
			baos = new ByteArrayOutputStream();
			dataOutputStream = new DataOutputStream(baos);

			int total = 0;
			int readbytes;
			byte[] buffer = new byte[BUFFER_SIZE];

			int max = Math.min(len, BUFFER_SIZE); // 当次读取最大字节

			while ((readbytes = inputStream.read(buffer, 0, max)) > 0) {
				dataOutputStream.write(buffer, 0, readbytes);
				total += readbytes;
				if (total >= len) {
					break;
				}
				max = Math.min(BUFFER_SIZE, len - total);
			}
		} catch (Exception e) {
			throw new FrameworkException("读取流信息失败", e);
		} finally {
			if (dataOutputStream != null) {
				try {
					dataOutputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return baos.toByteArray();
	}

}
